﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SpringGraph.ForceLayout;
using SpringGraph.Extensions;

namespace SpringGraph
{
    public class GraphNode : Node
    {
        public Control View
        {
            get;
            set;
        }

        public Item Item
        {
            get;
            set;
        }

        public GraphDataProvider Context
        {
            get;
            set;
        }

        public GraphNode(Control view, GraphDataProvider context, Item item)
            : base()
        {
            View = view;
            Context = context;
            Item = item;
        }

        public double NodeX
        {
            get
            {
                if (View != null)
                    return View.GetX();
                else
                    return 0;
            }
            set
            {
                if (View != null && Item.OkToMove())
                {
                    View.SetX(value);
                    Context.LayoutChanged = true;
                }
            }
        }

        public double NodeY
        {
            get
            {
                if (View != null)
                    return View.GetY();
                else
                    return 0;
            }
            set
            {
                if (View != null && Item.OkToMove())
                {
                    View.SetY(value);
                    Context.LayoutChanged = true;
                }
            }
        }

        public double NodeRepulsion
        {
            get
            {
                var result = Context.DefaultRepulsion;

                if (View != null)
                {
                    var r = (View.GetRealHeight() + View.GetRealWidth()) * Context.RepulsionFactor;

                    if (r > 0)
                        result = r;
                }

                return result;
            }
        }

        public override void Refresh()
        {
            this.X = NodeX;
            this.Y = NodeY;
            this.Repulsion = NodeRepulsion;
        }

        public override void Commit()
        {
            NodeX = this.X;
            NodeY = this.Y;
        }
    }
}
